let starttime = Date.now();
import axios from 'axios';
import crypto from 'crypto';
export let youdaoTranslate = async (text: string) => {
	let youdaoID = '1c9e91583cd7f940';
	let youdaoKey = 'll6iuVgNLpOOXkCy96z6RauplOfOS3g0';

	const salt = new Date().getTime();
	const curtime = Math.round(new Date().getTime() / 1000);
	let query = '  hello super owner this  is  your word ';
	query = text;
	// 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
	const from = 'auto';
	const to = 'zh-CHS';
	const vocabId = 'super';

	function truncate(q) {
		const len = q.length;
		if (len <= 20) return q;
		return q.substring(0, 10) + len + q.substring(len - 10, len);
	}

	const str1 = youdaoID + truncate(query) + salt + curtime + youdaoKey;
	const sign = crypto.createHash('sha256').update(str1).digest('hex');
	try {
		return await axios
			.post('https://openapi.youdao.com/api', null, {
				params: {
					q: query,
					appKey: youdaoID,
					salt: salt,
					from: from,
					to: to,
					sign: sign,
					signType: 'v3',
					curtime: curtime,
					vocabId: vocabId,
					domain: 'computers',
				},
			})
			.then((response) => {
				return Promise.resolve(response.data.translation[0]);
			})
			.catch((error) => {
				console.error(error);
				return Promise.reject(error);
			});
	} catch (e) {
		console.log(e);
		return Promise.reject(e);
	}
};

// 创建异步运行环境隔离异步操作, 消除异步传染性 ,使用JavaScript同步事件循环等待异步操作完成

// run函数提供执行环境
function run(func): any {
	// 定义cache来进行缓存
	const cache = {
		status: 'pending',
		data: null,
		err: null,
	};
	// 将原来异步函数进行缓存
	const beforeAsyncFn = youdaoTranslate;
	// 重写myFetch函数
	youdaoTranslate = (...args): any => {
		// 如果发现状态已经不是pending 就返回
		if (cache.status !== 'pending') return cache;
		// 通过抛出错误来执行异步数据请求
		throw beforeAsyncFn(...args)
			.then((res) => {
				// 成功更改缓存状态
				cache.status = 'fulfilled';
				cache.data = res;
			})
			.catch((err) => {
				// 失败改变缓存状态
				cache.status = 'rejected';
				cache.err = err;
			});
	};

	let result = { data: null };
	let done = false;

	try {
		// 使用try 调用原函数 捕获错误
		result = func();
		done = true;
	} catch (err) {
		// 判断返回值是否是promise
		if (err instanceof Promise) {
			// 当通过异常抛出的 promise 发生回调 重新调用 原函数
			err.finally(() => {
				result = func();
				done = true;
				// 还原原始请求方法 不造成污染
				youdaoTranslate = beforeAsyncFn;
			});
		}
	}

	while (!done) {
		// 使用同步循环等待异步操作完成
		deasync.loopWhile(() => !done);
	}
	return result?.data;
}

// 引入 deasync 库来同步等待
// const deasync = require('deasync');
import deasync from 'deasync';
// 运行
export const youdaoSynch = (text) => {
	const main = () => {
		const data = youdaoTranslate(text);
		return data;
	};
	const result = run(main);
	return result;
};
// console.log('start');
// console.log(youdaoSynch('WSL~##~ and linux~##~ are the~##~ same'));

// console.log('end');

// module.exports = youdaoSynch;
